package ca.inrs.ete.app.shopx;
import android.content.Intent;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import ca.inrs.ete.app.shopx.util.Constants;

public class SHOPFilesViewAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
	public enum VIEW_MODE {VIEW_MODE_IMAGE, VIEW_MODE_PAGER};

	private SHOPFilesView mActivity = null;
	private Uri[]         mImages  = null;

	private final SHOPFilesViewTumbnailGenerator bmpGen = new SHOPFilesViewTumbnailGenerator();

	public SHOPFilesViewAdapter(SHOPFilesView a) {
		mActivity = a;
	}

	public void setImages(Uri[] images) {
		mImages =  images;
	}

	public int getCount() {
		return (mImages == null) ? 0 : mImages.length;
	}

	public Object getItem(int position) {
		return null;
	}

	public long getItemId(int position) {
		return mImages[position].hashCode();
	}

	// create a new ImageView for each item referenced by the Adapter
	public View getView(int position, View convertView, ViewGroup parent) {
		final int sz = (int) mActivity.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
		final int sp = (int) mActivity.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

		ImageView imageView;
		if (convertView == null) {  // if it's not recycled, initialize some attributes
			imageView = new ImageView(mActivity);
			imageView.setLayoutParams(new GridView.LayoutParams(sz, sz));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(sp, sp, sp, sp);
		} else {
			imageView = (ImageView) convertView;
		}

		bmpGen.generateBitmap(mImages[position], imageView, sz, sz);

		return imageView;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		final SHOPPreferences prefs = new SHOPPreferences();
		prefs.readValues( PreferenceManager.getDefaultSharedPreferences(mActivity) );

		switch (prefs.getImageMode()) {
		case VIEW_MODE_IMAGE: {
			Intent viewIntent = new Intent(Intent.ACTION_VIEW);
			viewIntent.setDataAndType(mImages[position], "image/png");
			mActivity.startActivity(viewIntent);
			break;
		}
		case VIEW_MODE_PAGER: {
			Intent viewIntent = new Intent(Intent.ACTION_VIEW, mActivity.getSrcUri());
			viewIntent.addCategory(mActivity.getString(R.string.app_intent_category_image_pager));
			viewIntent.putExtra(Constants.INTENT_EXTRA_INT, position);
			mActivity.startActivity(viewIntent);
			break;
		}
		default: break;
		}
	}
}

